package com.sangmo.fts.process.factoring.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.fts.basic.model.FileUpload;
import com.sangmo.fts.basic.service.FileUploadService;
import com.sangmo.fts.process.factoring.model.FfContract;
import com.sangmo.fts.process.receivable.model.RpfContract;
import com.sangmo.fts.process.receivable.service.RpfContractEntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class FfContractDocumentService {

    @Autowired
    private FfContractEntityService ffContractEntityService;

    @Autowired
    private FileUploadService fileUploadService;

    public FileUpload createBuyerConfirmDoc(Long contractId, Long fileUploadId) {
        FfContract contract = ffContractEntityService.get(contractId);
        if (contract.isBuyerConfirm()) {
            throw new ServiceException(StandardErrors.EXTERNAL_ERROR.getStatus(), "error.ffContract.upload.permit.disabled");
        }
        contract.setBuyerConfirmDoc(fileUploadId);
        ffContractEntityService.save(contract);
        return create(contractId, fileUploadId, "FfContract.Buyer");
    }

    public FileUpload createSellerConfirmDoc(Long contractId, Long fileUploadId) {
        FfContract contract = ffContractEntityService.get(contractId);
        if (contract.isSellerConfirm()) {
            throw new ServiceException(StandardErrors.EXTERNAL_ERROR.getStatus(), "error.ffContract.upload.permit.disabled");
        }
        contract.setSellerConfirmDoc(fileUploadId);
        ffContractEntityService.save(contract);
        return create(contractId, fileUploadId, "FfContract.Seller");
    }


    public FileUpload create(Long contractId, Long fileUploadId, String refType) {
        FileUpload upload = fileUploadService.updateRef(fileUploadId, ""+contractId, refType);
        return upload;
    }
}
